﻿/*
 *	Copyright (c) 2009 Queensland University of Technology. All rights reserved.
 *	The QUT Bioinformatics Collection is open source software released under the 
 *	Microsoft Public License (Ms-PL): http://www.microsoft.com/opensource/licenses.mspx.
 */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace QUT.Bio.Util {
	public partial class ObjectListSelectionControl : UserControl {
		private IEnumerable<ISelectable> allItems;
		private ObservableCollection<ISelectable> available = new ObservableCollection<ISelectable>();
		private ObservableCollection<ISelectable> selected = new ObservableCollection<ISelectable>();

		public ObjectListSelectionControl() {
			InitializeComponent();
			availableList.ItemsSource = available;
			selectedList.ItemsSource = selected;
		}

		/// <summary>
		/// The universal set from which excluded, available and selected are drawn.
		/// <para>Set AllItems, then ExcludedItems, then SelectedItems.</para>
		/// <para>Ugly, but good enough for now.</para>
		/// </summary>
		public IEnumerable<ISelectable> AllItems {
			get {
				return allItems;
			}
			set {
				allItems = value;
				available.Clear();
				available.AddRange( allItems );
				selected.Clear();
			}
		}

		public string AvailableLabel {
			get {
				return availableText.Text;
			}
			set {
				availableText.Text = value;
			}
		}


		public IEnumerable<ISelectable> SelectedItems {
			get {
				return selected;
			}
			set {
				if ( selected != value ) {
					available.Clear();
					
					if ( AllItems != null ) {
						available.AddRange( AllItems );
					}
					
					selected.Clear();

					foreach ( var x in value ) {
						AddToSelection( x );
					}
				}
			}
		}

		public string SelectedLabel {
			get {
				return selectedText.Text;
			}
			set {
				selectedText.Text = value;
			}
		}

		public void AddToSelection ( ISelectable x ) {
			available.Remove( x );
			selected.InsertInOrder( x );
		}

		private void ItemSelected( object sender, SelectionChangedEventArgs e ) {
			ListBox sourceListBox = sender as ListBox;
			var sourceList = sourceListBox == availableList ? available : selected;
			var destinationList = sourceListBox == availableList ? selected : available;

			if ( sourceListBox.SelectedItem != null ) {
				var t = (ISelectable) sourceListBox.SelectedItem;
				sourceList.Remove( t );
				destinationList.InsertInOrder( t );
				sourceListBox.SelectedIndex = -1;
			}
		}
	}
}
